package cn.hznc.controller.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hznc.controller.service.permission.EmployeePermissionService;
import cn.hznc.domain.entity.*;
import cn.hznc.domain.request.DynamicMenuRequest;
import cn.hznc.exception.UserEx;
import cn.hznc.exception.UserException;
import cn.hznc.mapper.EmployeeMapper;
import cn.hznc.mapper.EmployeePermissionMapper;
import cn.hznc.repository.UserRepository;
import cn.hznc.utils.JwtHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserService {
    @Resource
    private UserRepository userRepository;
    @Resource
    private EmployeePermissionService employeePermissionService;
    @Resource
    private EmployeeMapper employeeMapper;
    @Resource
    private EmployeePermissionMapper employeePermissionMapper;


    /**
     * 根据登录信息进行查询
     * @param
     * @return
     */
    public UserEntity login(String name, String password , HttpServletRequest request , HttpServletResponse response) throws UserException {

        UserEntity user = userRepository.selectbyname(name);
        password = DigestUtils.md5DigestAsHex(password.getBytes());


        if (ObjectUtil.isNull(user)) {
            throw new UserException(UserEx.USERNAME_NOT_EXIST.getCode(), UserEx.USERNAME_NOT_EXIST.getMsg());
        }
        if (!(user.getPassword().equals(password))) {
            throw new UserException(UserEx.PASSWORD_ERROR.getCode(), UserEx.PASSWORD_ERROR.getMsg());
        }
        //user.setPassword(oldPassword);
//        HttpSession session = request.getSession();
//        session.setAttribute("X-token" , JwtHelper.createToken((long)user.getId() , user.getUsername()));
//        response.setHeader("X-token" , JwtHelper.createToken((long)user.getId() , user.getUsername()));
        user.setToken(JwtHelper.createToken((long)user.getId() , user.getUsername()));
        //设置进内存中
//        if(StringUtil.isNotEmpty(user.getUsername())){
//            SystemInit.user.setUsername(user.getUsername());
//        }
//        if(StringUtil.isNotEmpty(user.getPassword())){
//            SystemInit.user.setPassword(user.getPassword());
//        }
//        if(StringUtil.isNotEmpty(user.getToken())){
//            SystemInit.user.setToken(user.getToken());
//        }
//        if(ObjectUtil.isNotNull(user.getId())){
//            SystemInit.user.setId(user.getId());
//        }
        return user;

    }

    /**
     * 根据登录信息进行插入处理
     * @param
     * @return
     */
    @Transactional
       public void register (RegisterEntity registerEntity) throws UserException{

           UserEntity user = userRepository.selectbyname(registerEntity.getUsername());

           if(user!=null){
               throw new UserException(UserEx.USERNAME_EXIST.getCode(), UserEx.USERNAME_EXIST.getMsg());
           }else{
                String password = DigestUtils.md5DigestAsHex((registerEntity.getPassword()).getBytes());
                UserEntity userEntity = new UserEntity();
                userEntity.setPassword(password);
                userEntity.setUsername(registerEntity.getUsername());
//                registerEntity.setPassword(password);
                userRepository.insert(userEntity);
               EmployeeEntity employeeEntity = new EmployeeEntity();
               employeeEntity.setEmployeeName(registerEntity.getEmployeeName());
               UserEntity user1 = userRepository.selectbyname(registerEntity.getUsername());
               employeeEntity.setUserId(user1.getId());
               UserConnectionEntity userConnectionEntity = new UserConnectionEntity();
               userConnectionEntity.setRolesId(7);
               userConnectionEntity.setUserId(user1.getId());
               employeePermissionMapper.insert(userConnectionEntity);
               List<EmployeeEntity> employeeEntityList = employeePermissionService.queryAllEmployee();
               List<Integer> employeeNoList = new ArrayList<>();
               employeeEntityList.forEach(e ->{
                   employeeNoList.add(Integer.valueOf(e.getEmployeeNo()));
               });
               Collections.sort(employeeNoList);
               employeeEntity.setEmployeeNo(String.valueOf(employeeNoList.get(employeeNoList.size()-1)+1));
               employeeEntity.setDepartment("刀具二厂");
               employeeEntity.setCompany("株洲钻石切削刀具股份有限公司");
               employeeMapper.insert(employeeEntity);
           }
       }




        public  List<DynamicMenuRequest> showDynamicMenu(UserEntity user , HttpServletRequest request)throws UserException{

            UserEntity user1 = userRepository.selectbyname(user.getUsername());

           //String s = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());

            if (ObjectUtil.isNull(user1)) {
                throw new UserException(UserEx.USERNAME_NOT_EXIST.getCode(), UserEx.USERNAME_NOT_EXIST.getMsg());
            }
            if (!(user1.getPassword().equals(user.getPassword()))) {
                throw new UserException(UserEx.PASSWORD_ERROR.getCode(), UserEx.PASSWORD_ERROR.getMsg());
            }

             List <Integer> rolseId =   userRepository.selectRolesByUid(user1.getId());

            if(CollectionUtil.isEmpty(rolseId)){
                return new ArrayList<>();
            }
             List <Integer> menuId = userRepository.selectMenuIdByRolse(rolseId);

             if(CollectionUtil.isEmpty(menuId)){
                 return new ArrayList<>();
             }
             List<MenuEntity> list = userRepository.selectMenuByMenuId(menuId);

           //去重
          //  List<MenuEntity> list2 = list.stream().distinct().collect(Collectors.toList());

            HttpSession session = request.getSession();
            session.setAttribute("user" , user1);
            return   findChild(list,1);


        }

        public List<DynamicMenuRequest> findChild(List<MenuEntity> list , Integer fatherId){

                List<DynamicMenuRequest> list2 = new ArrayList<>();

                if(fatherId != null ){
                    List <MenuEntity> ByFatherList = list.stream().filter(item-> fatherId.intValue()==item.getFatherId().intValue()).collect(Collectors.toList());

                    List<MenuEntity>  ByOtherList = list.stream().filter(item-> fatherId.intValue()!=item.getFatherId().intValue()).collect(Collectors.toList());

                    for (MenuEntity menuEntity:ByFatherList) {

                        DynamicMenuRequest dynamicMenuRequest =  new DynamicMenuRequest();

                        dynamicMenuRequest.setId(menuEntity.getId());
                        dynamicMenuRequest.setMenuName(menuEntity.getMenuName());
                        dynamicMenuRequest.setMenuUrl(menuEntity.getMenuUrl());
                        dynamicMenuRequest.setFatherId(menuEntity.getFatherId());

                        //直接使用==比较Integer类型 在数值超过127 或-128时会返回false
                        if(menuEntity.getFatherId().intValue() == fatherId.intValue()){
                            dynamicMenuRequest.setChild(findChild(ByOtherList, dynamicMenuRequest.getId()));
                            list2.add(dynamicMenuRequest);
                        }
                    }
                }
                return  list2;
        }


        public List<RolesEntity> selectRoles (Integer pageNum, Integer pageSize){
            List<RolesEntity>  rolesEntityList = userRepository.selectRoles(pageNum,pageSize);
           return rolesEntityList;
        }


    public Object getEmployeeNameByUserName(Integer userId) {
        return userRepository.getEmployeeNameByUserName(userId);
    }
}
